<template>
  <div>
    <userDetail v-if="userListShowF" :userListShowF='userListShowF' :roleId='roleId'
                @returnClick="returnClick"></userDetail>
    <div class="faultHandlingMode zy-content " v-if="!userListShowF">
      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('角色名称')}}</p>
              <div class="ipt">
                <Input type="text" v-model="paramsList.name" :placeholder="`${$t('common.inputInfo')}`"
                       class="inputBorder" :maxlength="32" clearable></Input>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('状态')}}</p>
              <div class="ipt">
                <Select v-model="paramsList.status" filterable placeholder="">
                  <Option v-for="(item,index) of statusArr" :value="item.id" :key="index">{{ item.name }}</Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" v-if="checkBtnPermission.rolePage" @click="changeNum()">
                  {{ $t('common.Query') }}
                </Button>
                <Button
                    class="reset-btn"
                    @click="reset()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button v-if="checkBtnPermission.roleInsert" @click="createfaultCodeShowH">{{$t('common.New')}}</Button>
            <Button @click="getTableColumns(columns)">
                {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
            </Button>
        </div>
        <div class="tableContent">
          <Table ellipsis ref="selection"  class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList" :data="dataArr">
            <template slot-scope="{ row ,index}" slot="action">
              <auto-place-children>
               <span class="operationBtn" @click="createfaultCodeShowH(row)" v-has="'roleUpdate'">
                 <i class="iconfont zy-common-bianji"></i>
                 {{ $t('common.Edit') }}</span>

                <span class="operationBtn" @click="userListClick(row)" v-if="checkBtnPermission.roleGetUsersByRoleId"><i
                    class="iconfont zy-common-liebiao"></i>{{$t('查看用户列表')}}</span>

                <span class="operationBtn" @click="authorizationClick(row,1)"
                      v-if="checkBtnPermission.roleUpdateMenuAndPrivilege"><i class="iconfont zy-common-shouquan"></i>{{$t('授权')}}</span>

                <span class="operationBtn" @click="allotClick(row)" v-if="checkBtnPermission.roleGetFieldByRoleId"><i
                    class="iconfont zy-common-shezhi"></i>{{$t('字段权限')}}</span>

                <span class="operationBtn" @click="delPrrShowH(row)" v-if="checkBtnPermission.roleDelete"><i
                    class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>

                <span class="operationBtn" @click="enableClick(row)"
                      v-if="checkBtnPermission.roleInsert&&row.status==0"><i class="iconfont zy-common-chenggong1"></i>{{$t('启用')}}</span>

                <span class="operationBtn" @click="enableClick(row)"
                      v-if="checkBtnPermission.roleInsert&&row.status==1"><i
                    class="iconfont zy-common-jinyong"></i>{{ $t('common.disable') }}</span>

                <span class="operationBtn" @click="openCopyModel(row)"
                      v-has="'roleCopy'">
                <i class="iconfont zy-common-jinyong"></i>
                {{ $t('common.CopyandAdd') }}
              </span>

              </auto-place-children>
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total"/>
          <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
        </div>
      </div>

      <Modal :mask-closable="false"
          v-model="create"
          :title="addtitle"
          class="modal-content-layout"
          :loading="loading">
        <Form class="formList" ref="addFrom" :model="formItem" label-position="top">
          <FormItem :label="$t('角色名称')" required>
            <Input type="text" v-model="formItem.name" :placeholder="`${$t('common.inputInfo')}`" class="inputBorder"
                   :maxlength="32">
            </Input>
          </FormItem>
          <FormItem :label="$t('数据权限')" required >
            <Select v-model="formItem.dataScope">
              <Option v-for="(item, index) in dataScopes"
                      :key="index"
                      :label="item.label"
                      :value="item.value">
              </Option>
            </Select>
          </FormItem>
          <FormItem :label="$t('状态')" class="textlab" required>
            <RadioGroup v-model="formItem.status">
              <Radio label="0">{{ $t('common.disable') }}</Radio>
              <Radio label="1">{{$t('启用')}}</Radio>
            </RadioGroup>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="addOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>

      <Modal :mask-closable="false"
          v-model="delFaultCodeShowF"
          :title="$t('common.Delete')"
          class="modal-title-layout"
          :loading="loading">
        <div class="icon red">
          <i class="iconfont zy-common-shanchu"></i>
        </div>
        <p class="title">
          <span>{{ $t('common.confirmDelete') }}</span>
        </p>
        <div slot="footer">
          <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>

      <Modal :mask-closable="false"
          v-model="authorizationShowF"
          :title="`${$t('授权')}(${activeItem.name})`"
          class="modal-content-layout"
          :loading="loading">
<!--        <p style="padding-bottom: 10px;font-weight: bold">{{activeItem.name}}</p>-->
        <Tree :data="data2" show-checkbox ref="tree" :render="renderContent"></Tree>
        <div slot="footer">
          <Button type="default" @click="authorizationShowF = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="authorizationOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>

      <Modal :mask-closable="false"
          v-model="allotShowF"
          :title="$t('字段权限')"
          class="modal-content-layout"
          width="600">
        <CheckboxGroup v-model="allotCheckList">
          <Row>
            <Col span="8" v-for="(item,index) in allotGroup" :key="index" style="line-height:35px">
              <Checkbox :label="item.id" :key="index">{{ item.name }}</Checkbox>
            </Col>
          </Row>
        </CheckboxGroup>
        <div slot="footer">
          <Button type="default" @click="allotShowF = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="allotOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>

      <Modal :mask-closable="false"
          v-model="copyModel"
          :title="$t('common.CopyandAdd')"
          class="modal-content-layout"
          :loading="loading">

        <Form class="formList" ref="addFrom" :model="formItem" label-position="top">
          <FormItem :label="$t('角色名称')" required>
            <Input type="text" v-model="formItem.name" :placeholder="`${$t('common.inputInfo')}`" class="inputBorder"
                   :maxlength="32">
            </Input>
          </FormItem>
          <FormItem :label="$t('数据权限')" required >
            <Select v-model="formItem.dataScope">
              <Option v-for="(item, index) in dataScopes"
                      :key="index"
                      :label="item.label"
                      :value="item.value">
              </Option>
            </Select>
          </FormItem>
          <FormItem :label="$t('状态')" class="textlab" required>
            <RadioGroup v-model="formItem.status">
              <Radio label="0">{{ $t('common.disable') }}</Radio>
              <Radio label="1">{{$t('启用')}}</Radio>
            </RadioGroup>
          </FormItem>
        </Form>

        <Tree :data="data2" show-checkbox ref="tree" :render="renderContent"></Tree>

        <div slot="footer">
          <Button type="default" @click="copyModel = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="copySubmit">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>
    </div>
  </div>


</template>

<script>
import {Input, Checkbox, Icon, Table, Page, Select, Option, Modal, Form, FormItem, InputNumber} from 'view-design';
import userDetail from './modal/userDetail'
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "faultHandlingMode",
  components: {Input, Checkbox, Icon, Table, Page, Select, Option, Modal, Form, FormItem, InputNumber, userDetail},
    mixins:[toggleTableOperation],
  data() {
    return {
      dataScopes: [{
        value: 1,
        label: this.$t('全部数据权限')
      }, {
        value: 2,
        label: this.$t('本部门数据权限')
      }, {
        value: 3,
        label: this.$t('本部门及以下数据权限')
      }, {
        value: 4,
        label: this.$t('仅本人数据权限')
      }],
      copyModel: false,
      roleId: '',
      delUserShowF: false,
      allotGroup: [],
      allotCheckList: [],
      allotUserId: "",
      allotShowF: false,
      userParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        pageSizeOption: [10, 20, 30, 40],
      },
      userData: [],
      userCol: [
        {
          key: 'selection',
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          // title: '工号',
          title: `${ this.$t('工号') }`,
          key: 'empno',
          align: 'center'
        },
        {
          // title: '用户名',
          title: `${ this.$t('用户名') }`,
          key: 'realname',
          align: 'center'
        },
      ],
      data2: [
        {
          name: `${ this.$t('所有菜单') }`,
          expand: true,
          children: [
            {
              name: 'PC',
              expand: true,
              children: []
            },
            {
              name: 'PDA',
              expand: true,
              children: []
            }
          ]
        }
      ],
      statusArr: [
        {id: '2', name: this.$t('全部')},
        {id: 1, name: this.$t('启用')},
        {id: 0, name: this.$t('common.disable')}
      ],
      userListShowF: false,
      authorizationShowF: false,
      formItem: {},
      addtitle: "",
      allCheck: false,
      loading: false,
      create: false,
      update: false,
      selectionId: [],
      selectionIdShow: false,
      paramsList: {
        status: '2'
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      columns: [
        // {
        //     key:'selection',
        //     type: 'selection',
        //     width: 60,
        //     align: 'center'
        // },
        {
          // title: '角色名称',
          title: `${ this.$t('角色名称') }`,
          key: 'name',
          align: 'center',
            resizable: true
        },
        {
          // title: '状态',
          title: `${ this.$t('状态') }`,
          key: 'status',
          align: 'center',
            resizable: true,tooltip: true,
          render: (h, params) => {
            if (params.row.status == 1) {
              return h('div', [
                h('span', {style: {}}, this.$t("启用"))
              ]);
            }
            if (params.row.status == 0) {
              return h('div', [
                h('span', {style: {}}, this.$t('common.disable'))
              ]);
            }
          }
        },
        // {
        //     title: '查看用户列表',
        //     key: 'materialType',
        //     align: 'center'
        // },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          width: 350,
          // width: this.util.autoWidth(450, 600),
          align: "center",
            fixed:"right"
        }
      ],
      dataArr: [],
      materialTypeArr: [],
      materialTypeArr1: [],
      importFaultCodeShowF: false,//是否显示批量导入弹窗
      delFaultCodeShowF: false,//是否显示删除弹窗
      pageSizeOption: [10, 20, 30, 40],
      delIds: null,
      selection: [],
      authorizationList: [],
      authorizationRole: "",
      checkBtnPermission: {},
      userCancel: [],
      activeItem:{}
    }
  },
    created() {
      this.getTableColumnsWidth(this.columns)
    },
    mounted() {
    this.searchList();
    let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
    for (let item of itemList) {
      if (item.code == "rolePage") {
        this.checkBtnPermission.rolePage = true
      }
      if (item.code == "roleDelete") {
        this.checkBtnPermission.roleDelete = true
      }
      if (item.code == "roleInsert") {
        this.checkBtnPermission.roleInsert = true
      }
      if (item.code == "roleUpdate") {
        this.checkBtnPermission.roleUpdate = true
      }
      if (item.code == "roleUpdateMenuAndPrivilege") {
        this.checkBtnPermission.roleUpdateMenuAndPrivilege = true
      }
      if (item.code == "roleGetUsersByRoleId") {
        this.checkBtnPermission.roleGetUsersByRoleId = true
      }
      if (item.code == "roleGetFieldByRoleId") {
        this.checkBtnPermission.roleGetFieldByRoleId = true
      }


    }

  },
  methods: {
    openCopyModel(row){
      this.formItem = {};

      this.formItem.status = row.status.toString();
      this.formItem.name = '';
      this.formItem.dataScope = row.dataScope;
      this.formItem.id = row.id;

      this.authorizationClick(row,2);

      this.copyModel = true;
    },
    copySubmit (){
      let list = [];
      let menuList = [];
      let privilegeList = [];
      list = this.$refs.tree.getCheckedNodes()
      for (let item of list) {
        if (item.name == "PC" || item.name == `${ this.$t('所有菜单') }` || item.name == "PDA") {

        } else {
          if (item.type == 1) {
            menuList.push(item.id)
          } else {
            privilegeList.push(item.id)
          }
        }
      }

      let params = {
        ...this.formItem,
        menuList: menuList,
        privilegeList: privilegeList
      }

      this.axios({
        method: 'post',
        url: "/basic/role/copyAndAdd",
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.changeNum();
          this.copyModel = false;
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    returnClick() {
      this.userListShowF = false
    },
    allotOk() {
      this.axios({
        method: 'post',
        url: '/basic/role/updateField',
        data: {
          roleId: this.allotUserId,
          fieldList: this.allotCheckList
        }
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.data)
          this.allotShowF = false
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    allotClick(row) {
      this.allotShowF = true
      this.allotCheckList = []
      this.allotUserId = row.id
      this.axios({
        method: 'get',
        url: '/basic/role/getFieldByRoleId',
        params: {
          id: row.id
        }
      }).then(res => {
        if (res.code === 200) {
          this.allotGroup = res.data
          if (res.data) {
            for (let item of res.data) {
              if (item.checked == true) {
                this.allotCheckList.push(item.id)
              }
            }
          }
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    authorizationOk() {
      let list = [];
      let menuList = [];
      let privilegeList = [];
      list = this.$refs.tree.getCheckedNodes()
      for (let item of list) {
        if (item.name == "PC" || item.name == `${ this.$t('所有菜单') }` || item.name == "PDA") {

        } else {
          if (item.type == 1) {
            menuList.push(item.id)
          } else {
            privilegeList.push(item.id)
          }
        }
      }
      this.axios({
        method: 'post',
        url: "/basic/role/updateMenuAndPrivilege",
        data: {
          roleId: this.authorizationRole,
          menuList: menuList,
          privilegeList: privilegeList
        }
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.authorizationShowF = false;
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    authorizationClick(row,type) {
      this.authorizationRole = row.id
      this.activeItem = row;
      if(type===1){
        this.authorizationShowF = true;
      }

      this.axios({
        method: 'get',
        url: "/basic/role/getMenuAndPrivilegeByRoleId",
        params: {
          id: row.id
        }
      }).then(res => {
        if (res.code === 200) {
          this.data2 = [
            {
              name: `${ this.$t('所有菜单') }`,
              expand: true,
              children: [
                {
                  name: 'PC',
                  expand: true,
                  children: []
                },
                {
                  name: 'PDA',
                  expand: true,
                  children: []
                }
              ]
            }
          ],
              this.data2[0].children[0].children = res.data[0]
          this.data2[0].children[1].children = res.data[1]
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    userListClick(row) {
      this.userListShowF = true;
      this.roleId = row.id
    },
    renderContent(h, {root, node, data}) {
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%',
          fontSize: '15px'
        }
      }, [
        h('span', [
          h('span', data.name)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        })
      ]);
    },
    reset(){
      this.paramsList = {
        status: '2'
      };
      this.changeNum();
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {//查询列表

      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        name: this.paramsList.name,
        // status:this.paramsList.status
      };
      if (this.paramsList.status == 2) {
        params.status = ""
      } else {
        params.status = this.paramsList.status
      }
      this.axios({
        method: 'get',
        url: '/basic/role/page',
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    createfaultCodeShowH(row) {//点击增加或编辑
      this.$refs.addFrom.resetFields();
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`
        this.formItem.status = row.status.toString();
        this.formItem.name = row.name;
        this.formItem.dataScope = row.dataScope;
        this.formItem.id = row.id;
      } else {
        this.addtitle = `${this.$t('common.New')}`
        this.formItem.sort = 1;
        this.formItem.status = "1";
        this.formItem.name = "";
        this.formItem.id = "";

      }
      this.create = true;
    },
    enableClick(row) {
      let params = {
        name: row.name,
        id: row.id
      }
      let message = ""
      if (row.status == 0) {
        params.status = 1
        message = this.$t("启用成功")
      } else {
        params.status = 0
        message = this.$t("禁用成功")
      }
      this.axios({
        method: 'post',
        url: '/basic/role/update',
        data: params
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$Message.success(message)
          this.changeNum();
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    addOk() {
      if (this.formItem.name === null || this.formItem.name === undefined || this.formItem.name === "") {
        this.$Message.warning(({content: this.$t("请输入角色名称"), duration: 6, closable: true}));
        return false;
      }
      if (this.formItem.status === null || this.formItem.status === undefined || this.formItem.status === "") {
        this.$Message.warning(({content: this.$t("请选择状态"), duration: 6, closable: true}));
        return false;
      }
      this.loading = true;
      if (this.formItem.id) {
        this.axios({
          method: 'post',
          url: '/basic/role/update',
          data: this.formItem
        }).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.changeNum();
            this.$Message.success(res.msg);
            this.create = false;
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        })
      } else {
        this.axios({
          method: 'post',
          url: '/basic/role/insert',
          data: this.formItem
        }).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.changeNum();
            this.$Message.success(res.msg);
            this.create = false;
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        })
      }

    },
    delPrrShowH(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds = row.id;

    },
    deleteOk() {
      this.loading = true;
      this.axios({
        method: 'post',
        url: '/basic/role/delete',
        params: {
          id: this.delIds
        }
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success(res.msg);
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.faultHandlingMode {
  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;
    }
  }

}
</style>

<style lang="scss">

</style>
